package com.ai.planttrees.service.impl;

import com.ai.planttrees.dao.RuleBodyMapper;
import com.ai.planttrees.dao.RuleTitleMapper;
import com.ai.planttrees.model.RuleBody;
import com.ai.planttrees.model.RuleTitle;
import com.ai.planttrees.service.RuleTitleService;
import com.ai.planttrees.core.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by CodeGenerator on 2018/05/04.
 */
@Service
@Transactional
public class RuleTitleServiceImpl extends AbstractService<RuleTitle> implements RuleTitleService {
    @Resource
    private RuleTitleMapper ruleTitleMapper;
    @Resource
    private RuleBodyMapper ruleBodyMapper;

    @Override
    public List<RuleTitle> selRule() {
        List<RuleTitle> ruleTitles = ruleTitleMapper.selAll();
        for (RuleTitle ruleTitle : ruleTitles) {
            List<RuleBody> ruleBodies = ruleBodyMapper.selByTit(ruleTitle.getId());
            ruleTitle.setRuleBodies(ruleBodies);
        }
        return ruleTitles;
    }
    //判断是否活动过期
    @Override
    public Map isOverdue() {
        Map map = new HashMap();
        map.put("code",false);
        RuleBody ruleBody = ruleBodyMapper.selectByPrimaryKey(1);
        String [] times = ruleBody.getBody().split(",");
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d1 = formatter.parse(times[0]);
            Date d2= formatter.parse(times[1]);
            Date now = new Date();
            if(now.getTime()==d1.getTime() || now.getTime()==d2.getTime()){
                map.put("code",true);
                return map;
            }
            Calendar date = Calendar.getInstance();
            date.setTime(now);

            Calendar begin = Calendar.getInstance();
            begin.setTime(d1);

            Calendar end = Calendar.getInstance();
            end.setTime(d2);
            end.add(Calendar.DATE,1);

            if (date.after(begin) && date.before(end)) {
                map.put("code",true);
                return map;
            }else{
                if(date.before(begin)){
                    map.put("msg","活动未开始");
                }
                if(date.after(end)){
                    map.put("msg","活动已结束");
                }
                return map;
            }

        } catch (ParseException e) {
            e.printStackTrace();
            return map;
        }
    }


}
